/*
 * Copyright (c) 2023, 2023,yzc.cn All rights reserved.
 *
 */
package com.crmapi.controller;


import com.crmapi.pojo.Result;
import io.swagger.annotations.Api;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Project: SpringBootPro - FileUploadController</p>
 * <p>Powered by yzc On 2023-11-11 09:26:19</p>
 * <p>描述：<p>
 *
 * @author yzc [yzc0415@126.com]
 * @version 1.0
 * @since 17
 */
@RestController
@CrossOrigin
@RequestMapping("/api_v1.0")
@Api(tags = "文件上传")
public class FileUploadController {

    private static final String DIR = "/attachment";

    //获取根目录
    private static final String root;

    static {
        try {
            root = ResourceUtils.getURL("classpath:").getPath() + "static";
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 单文件上传
     *
     * @return
     */
    @PostMapping("/file")
    public Result uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        //获得新的文件名字
        String FileName = getNewFileName(file.getOriginalFilename());

        //获得文件所在目录
        String Directory = getNewDirectory(request);
        //根据目录和新的文件名生成目录路路径
        String path = Directory + FileName;
        File newFile = new File(root + path);
        //进行拷贝
        file.transferTo(newFile);
        return Result.success(path);
    }

    /**
     * 多文件上传
     *
     * @return
     */
    @PostMapping("/files")
    public Result uploadFiles(List<MultipartFile> fileList, HttpServletRequest request) throws FileNotFoundException {
        //获取根目录
        String root = ResourceUtils.getURL("classpath:").getPath() + "static";
        //存放返回路劲的集合
        List<String> newFilePath = new ArrayList<>();
        fileList.forEach(file -> {
            //获得新的文件名字
            String FileName = getNewFileName(file.getOriginalFilename());

            //获得目录
            String Directory = null;
            try {
                Directory = getNewDirectory(request);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            String path = Directory+FileName;
            //根据目录和新的文件名生成对应位置的文件
            File newFile = new File(root+path);
            //文件新路径保存到集合中
            newFilePath.add(path);
            //进行拷贝
            try {
                file.transferTo(newFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        return Result.success(newFilePath);
    }

    /**
     * 根据给定的文件生成新的文件名
     *
     * @param fileName
     * @return
     */
    String getNewFileName(String fileName) {
        //获取文件后缀
        int i = fileName.lastIndexOf(".");
        String substring = fileName.substring(i);
        //获得新的文件名
        String NewFileName = System.currentTimeMillis() + substring;
        return NewFileName;
    }

    String getNewDirectory(HttpServletRequest request) throws FileNotFoundException {
        //获取根目录
        //String root = request.getServletContext().getRealPath("/");
        // String root = ResourceUtils.getFile("classpath:").getAbsolutePath();

        //生成新目录
        String directory = DIR + "/" + getYMD() + "/";
        File file = new File(root+ directory);
        if (!file.exists()) {
            //如果文件不存在，创建文件
            file.mkdirs();
        }
        return directory;
    }


    /**
     * 获得生成文件上传日期
     *
     * @return
     */
    String getYMD() {
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return date.format(formatter);
    }


}
